<?php
class User_RestController extends Ac_Rest_Controller
{

    /**
        return one random listing
    */
    public function indexAction() {
           
        $max_count = Model_User::all(array('status' => Model_User::STATUS_ACTIVE))->count(); 

        $skip = rand(0, $max_count-1);
        $list = Model_User::all(array('status' => Model_User::STATUS_ACTIVE))->skip($skip)->limit(1);
        $list->rewind();
        $ele = $list->current();
        //echo 'max_count: '. $max_count."\n";
        //echo 'skip:'. $skip."\n";
        //echo '_id: '.$ele->_id;exit;

        $this->_helper->json($ele->exportRest());
    }

    /**
        return one specific listing
    */
    public function getAction() 
    {
        $id   = $this->_request->getParam('id');
        $ele  = Model_User::one(array('_id' => new MongoId($id)));
        if (empty($ele)) {
            throw new Ac_Exception_MissingInformation('User not found');
        }

        $this->_helper->json($ele->exportRest());
    }

    public function postAction() 
    {
        //var_dump($_POST);
        //echo 'post';exit;    
        return $this->putAction();
         
    }

        
    public function putAction() {
        $params = $this->_request->getParams();
        if ($params['id'] == 'login') {
            return $this->loginAction();
        } elseif ($params['id'] == 'signup')  {
            return $this->signupAction();
        } 
    }

    public function loginAction()
    {
        file_put_contents('/tmp/api-login.txt', print_r($_SERVER, true).print_r($_POST, true), FILE_APPEND);
        $username = !empty($_POST['username']) ? trim($_POST['username']) : '';
        $password = !empty($_POST['password']) ? trim($_POST['password']) : '';


        //validation
        if (empty($username)) {
            //echo 'title empty';exit;
            $this->getResponse()->setHttpResponseCode(406);
            throw new Ac_Exception_MissingInformation('Username is empty');
        }
        if (empty($password)) {
            //echo 'category empty';exit;
            $this->getResponse()->setHttpResponseCode(406);
            throw new Ac_Exception_MissingInformation('Password is empty');
        }

        //try to find him first
        if ($user = (Model_User::one(array('ph' => $username)))) { //try with the phone number
            
        } elseif ($user = (Model_User::one(array('email' => strtolower($username))))) {//try with the email
            
        } elseif ($user = (Model_User::one(array('username' => strtolower($username))))) {//try with the username
            
        } elseif ($user = (Model_User::one(array('phone' => $username)))) {//try with the phone number
            
        }

        //validation
        if (!empty($user)) {
            if(($user->username != $username && $user->email != $username && $user->phone != $username) || $user->password != Model_User::generatePassword($password)) {
                $this->getResponse()->setHttpResponseCode(406);
                throw new Ac_Exception_MissingInformation('Invalid Credential');
            }
            $user->sess     = uniqid(time().'-', true);
            $user->save();
        } else {
            file_put_contents('/tmp/api-login.txt', "\nUser not found\n", FILE_APPEND);
            $this->getResponse()->setHttpResponseCode(404);
            throw new Ac_Exception_MissingInformation('User not found');
        }
        //var_dump($user->exportRest());
        //$this->getResponse()->setHttpResponseCode(201);
        //$this->_helper->json($user->exportRest(true)); 
        file_put_contents('/tmp/api-login.txt', print_r($user->exportRest(true), true), FILE_APPEND);
        echo json_encode($user->exportRest(true));exit;
    }

    public function signupAction() 
    {
        $username = !empty($_POST['username']) ? $_POST['username'] : '';
        $email    = !empty($_POST['email']) ? $_POST['email'] : '';
        $phone    = !empty($_POST['phone']) ? $_POST['phone'] : '';
        $password = !empty($_POST['password']) ? $_POST['password'] : '';


        //validation
        if (empty($username)) {
            //echo 'title empty';exit;
            $this->getResponse()->setHttpResponseCode(406);
            throw new Ac_Exception_MissingInformation('Username is empty');
        }
        if (empty($email)) {
            //echo 'price empty';exit;
            $this->getResponse()->setHttpResponseCode(406);
            throw new Ac_Exception_MissingInformation('Email is empty');
        }
        if (empty($password)) {
            //echo 'category empty';exit;
            $this->getResponse()->setHttpResponseCode(406);
            throw new Ac_Exception_MissingInformation('Password is empty');
        }
        if (empty($phone)) {
            //echo 'category empty';exit;
            $this->getResponse()->setHttpResponseCode(406);
            throw new Ac_Exception_MissingInformation('Phone is empty');
        }

        //try to find him first
        if ($user = (Model_User::one(array('ph' => $phone)))) { //try with the phone number

        } elseif ($user = (Model_User::one(array('email' => strtolower($email))))) {//try with the email

        } elseif ($user = (Model_User::one(array('username' => strtolower($username))))) {//try with the email

        }


        //validation
        if (!empty($user)) {
            $this->getResponse()->setHttpResponseCode(409);
            throw new Ac_Exception_MissingInformation('User already exists');
        } else {
            $user = new Model_User();
            $user->username = $username;
            $user->email    = $email;
            $user->password = Model_User::generatePassword($password);
            $user->phone    = $phone;
            $user->newsletter = !empty($_POST['newsletter']);
            $user->status   = Model_User::STATUS_ACTIVE;
            $user->sess     = uniqid(time(), true);
            $user->save();
        }

        //var_dump($user->exportRest());
        $this->getResponse()->setHttpResponseCode(201);
        //$this->_helper->json($user->exportRest(true)); 
        echo json_encode($user->exportRest(true));exit;
    }
}

